package com.mycontract.suitepro.base

import android.content.Intent
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModel
import com.mycontract.suitepro.ProjectConfig
import com.mycontract.suitepro.R
import com.mycontract.suitepro.components.dialog.LoadingDialog
import com.mycontract.suitepro.components.dialog.MessageDialog
import com.mycontract.suitepro.components.dialog.PermissionItem
import com.mycontract.suitepro.contract.ContractSignManager
import com.mycontract.suitepro.extend.*
import com.mycontract.suitepro.network.NetworkException
import com.mycontract.suitepro.utils.analytics.util.AnalyticsUtil
import com.vmadalin.easypermissions.EasyPermissions
import com.vmadalin.easypermissions.dialogs.DEFAULT_SETTINGS_REQ_CODE
import com.vmadalin.easypermissions.dialogs.SettingsDialog

const val REQ_CONTRACTSUITE_CODE_CONTRACTSUITE_PAGE_CONTRACTSUITE_PERMISSION: Int = 200
const val KEY_CONTRACTSUITE_PARAMS_CONTRACTSUITE_VIRTUAL_CONTRACTSUITE_BANK_CONTRACTSUITE_NAME: String =
    "KEY_PARAMS_VIRTUAL_BANK_NAME"
const val KEY_CONTRACTSUITE_PARAMS_CONTRACTSUITE_VIRTUAL_CONTRACTSUITE_BANK_CONTRACTSUITE_ACCOUNT: String =
    "KEY_PARAMS_VIRTUAL_BANK_ACCOUNT"
const val KEY_CONTRACTSUITE_PARAMS_CONTRACTSUITE_REPAY_CONTRACTSUITE_AMOUNT: String =
    "KEY_PARAMS_VIRTUAL_REPAY_AMOUNT"

abstract class BaseActivity : AppCompatActivity(),
    EasyPermissions.PermissionCallbacks,
    EasyPermissions.RationaleCallbacks {

    var ACTIVITY_CONTRACTSUITE_TAG: String = ""

    private lateinit var mContractSuiteLoadingContractSuiteDialog: LoadingDialog
    private var mContractSuitePermissionContractSuiteList: Array<String>? = null
    private var mContractSuitePermissionContractSuiteStatement: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ACTIVITY_CONTRACTSUITE_TAG = this::class.java.simpleName

        with(window) {
//            requestFeature(Window.FEATURE_CONTENT_TRANSITIONS)
//            exitTransition = Slide(Gravity.START).setDuration(300)
//            enterTransition = Slide(Gravity.END).setDuration(300)
//            exitTransition = Fade()
//            enterTransition = Slide()
        }
        //mFirebaseAnalytics = Firebase.analytics
        setContractSuiteFullContractSuiteScreenContractSuiteMode()
        ACTIVITY_CONTRACTSUITE_TAG = onContractSuiteBindingContractSuiteViewContractSuiteTag()
        setContentView(onContractSuiteBindingContractSuiteContentContractSuiteView())
//        setContentView(onBindingContentLayoutId())
        mContractSuiteLoadingContractSuiteDialog = LoadingDialog(this)
        setContractSuiteViewContractSuiteModelContractSuiteActions()
        onContractSuiteContentContractSuiteViewContractSuiteBinded()
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            val view = currentFocus
            if (view != null) {
                try {
                    if (canContractSuiteHideContractSuiteKeyboard(view, ev)) {
                        hideContractSuiteKeyboard()
                        val editText = view as EditText
                        editText.clearFocus()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            return super.dispatchTouchEvent(ev)
        }
        return window.superDispatchTouchEvent(ev) || onTouchEvent(ev)
    }

    override fun onResume() {
        super.onResume()
        val gType =
            "${ProjectConfig.CONTRACTSUITE_Product}_${this.onContractSuiteBindingContractSuiteViewContractSuiteTag()}_START".uppercase()
        AnalyticsUtil.saveHitPointInfo(
            type = gType,
            remark = System.currentTimeMillis().toString()
        )
    }

    override fun onPause() {
        super.onPause()
        val gType =
            "${ProjectConfig.CONTRACTSUITE_Product}_${this.onContractSuiteBindingContractSuiteViewContractSuiteTag()}_END".uppercase()
        AnalyticsUtil.saveHitPointInfo(
            type = gType,
            remark = System.currentTimeMillis().toString()
        )
    }

    /**绑定model*/
    protected abstract fun onContractSuiteBindingContractSuiteViewContractSuiteModel(): List<ViewModel>?

    /**绑定tag*/
    protected abstract fun onContractSuiteBindingContractSuiteViewContractSuiteTag(): String

    /**绑定视图开始*/
    protected abstract fun onContractSuiteBindingContractSuiteContentContractSuiteView(): View

    /**绑定视图开始*/
//    protected abstract fun onContractSuiteBindingContractSuiteContentContractSuiteLayoutContractSuiteId(): Int

    /**绑定视图完成*/
    protected abstract fun onContractSuiteContentContractSuiteViewContractSuiteBinded()

    private fun setContractSuiteViewContractSuiteModelContractSuiteActions() {
        val viewModelList = onContractSuiteBindingContractSuiteViewContractSuiteModel()
        if (!(viewModelList.isNullOrEmpty())) {
            viewModelList.forEach {
                if (it is BaseViewModelAction) {
                    it.getContractSuiteLoadingContractSuiteLiveContractSuiteData()
                        .observe(this) { showLoading ->
                            if (showLoading)
                                showContractSuiteLodingContractSuiteDialog()
                            else
                                dismissContractSuiteLoadingContractSuiteDialog()
                        }

                    it.getContractSuiteNetworkContractSuiteExceptionContractSuiteLiveContractSuiteData()
                        .observe(this) {
                            onContractSuiteHandleContractSuiteNetworkContractSuiteExcepton(it)
                        }
                }
            }
        }
    }

    protected fun showContractSuiteLodingContractSuiteDialog() {
        mContractSuiteLoadingContractSuiteDialog.showContractSuiteDialog(this)
    }

    protected fun dismissContractSuiteLoadingContractSuiteDialog() {
        mContractSuiteLoadingContractSuiteDialog.dismissContractSuiteDialog()
    }

    /**交给子类去实现*/
    open fun onContractSuiteHandleContractSuiteNetworkContractSuiteExcepton(networkException: NetworkException) {
        if (networkException.isContractSuiteAlter()) {
            MessageDialog.showContractSuiteDialog(
                supportFragmentManager,
                networkException.msg
            )
        } else {
            Toast.makeText(this, networkException.msg, Toast.LENGTH_LONG)
                .show()
        }
        if (networkException.msg.contains("User does not exist") or (networkException.msg.contains("Người dùng không tồn tại"))) {
//            startContractSuiteToContractSuiteNextContractSuiteActivityContractSuiteAndContractSuiteFinish<LoginInputMobileActivity>()
        }
    }

    /**交给子类去实现*/
    open fun onContractSuitePermissionsContractSuiteRequestContractSuiteAllContractSuitePass() {

    }

    /**交给子类去实现*/
    open fun onContractSuitePermissionsContractSuiteRequestContractSuiteSMSContractSuitePass(realAgree: Boolean) {

    }

    /**交给子类去实现*/
    open fun onContractSuitePermissionsContractSuiteRequestContractSuiteHomeSMSContractSuitePass(realAgree: Boolean) {

    }

    /**交给子类去实现*/
    open fun onContractSuitePermissionsContractSuiteRequestContractSuitePhoneStateContractSuitePass(realAgree: Boolean) {

    }

    /**交给子类去实现*/
    open fun onContractSuitePermissionsContractSuiteRequestContractSuiteContactsContractSuitePass(realAgree: Boolean) {

    }

    /**交给子类去实现*/
    open fun onContractSuitePermissionsContractSuiteRequestContractSuiteCalllogContractSuitePass(realAgree: Boolean) {

    }

    open fun requestContractSuiteSpecContractSuitePermissions(permissionList: Array<String>) {
        try {
            startContractSuiteEasyContractSuitePermissions(
                getString(R.string.contract_suite_permissions_all),
                permissionList
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    open fun requestContractSuiteSmsContractSuitePermission(reqCode: Int) {
        try {
            EasyPermissions.requestPermissions(
                this,
                getString(R.string.contract_suite_permissions_sms),
                reqCode,
                *(arrayOf(android.Manifest.permission.READ_SMS))
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    open fun requestContractSuitePhoneStateContractSuitePermission(reqCode: Int) {
        try {
            EasyPermissions.requestPermissions(
                this,
                getString(R.string.contract_suite_permissions_phone),
                reqCode,
                *(arrayOf(android.Manifest.permission.READ_PHONE_STATE))
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    open fun requestContractSuiteContactsContractSuitePermission(reqCode: Int) {
        try {
            EasyPermissions.requestPermissions(
                this,
                getString(R.string.contract_suite_permissions_contact),
                reqCode,
                *(arrayOf(android.Manifest.permission.READ_CONTACTS))
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    open fun requestContractSuiteCalllogContractSuitePermission(reqCode: Int) {
        try {
            EasyPermissions.requestPermissions(
                this,
                getString(R.string.contract_suite_permissions_call_log),
                reqCode,
                *(arrayOf(android.Manifest.permission.READ_CALL_LOG))
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)


        println("------权限回来了：1")
        println(requestCode)
        permissions.forEach {
            println(it)
        }
        println("------权限回来了：2")
        grantResults.forEach {
            println(it)
        }


        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onRationaleAccepted(requestCode: Int) {
        mContractSuitePermissionContractSuiteStatement?.let {
            mContractSuitePermissionContractSuiteList?.let { list ->
                startContractSuiteEasyContractSuitePermissions(it, list)
            }
        }
    }

    override fun onRationaleDenied(requestCode: Int) {
        println("------权限拒绝了：2")
        println(requestCode)

    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        println("------权限拒绝了：")
        println(perms)

        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            SettingsDialog.Builder(this).build().show()

        } else {
            //区分短信
            if (requestCode == PermissionItem.TYPE_SMS) {
                onContractSuitePermissionsContractSuiteRequestContractSuiteSMSContractSuitePass(false)
            }
            if (requestCode == PermissionItem.TYPE_CONTRACTS) {
                onContractSuitePermissionsContractSuiteRequestContractSuiteContactsContractSuitePass(false)
            }
            if (requestCode == PermissionItem.TYPE_CALL_LOG) {
                onContractSuitePermissionsContractSuiteRequestContractSuiteCalllogContractSuitePass(false)
            }
            if (requestCode == PermissionItem.TYPE_PHONE_STATE) {
                onContractSuitePermissionsContractSuiteRequestContractSuitePhoneStateContractSuitePass(false)
            }
        }
//        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
//            SettingsDialog.Builder(this).build().show()
//        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {

        val isGrantedAll = isContractSuiteAgreeContractSuiteSpecContractSuitePermissions(
            mutableListOf(
                android.Manifest.permission.READ_SMS,
                android.Manifest.permission.READ_PHONE_STATE,
                android.Manifest.permission.READ_CONTACTS
            )
        )

        if (requestCode == PermissionItem.TYPE_SMS) {
            onContractSuitePermissionsContractSuiteRequestContractSuiteSMSContractSuitePass(true)
            if (isGrantedAll) {
                onContractSuitePermissionsContractSuiteRequestContractSuiteAllContractSuitePass()
            }

        } else if (requestCode == PermissionItem.TYPE_HOME_SMS) {
            onContractSuitePermissionsContractSuiteRequestContractSuiteHomeSMSContractSuitePass(true)
            if (isGrantedAll) {
                onContractSuitePermissionsContractSuiteRequestContractSuiteAllContractSuitePass()
            }

        } else if (requestCode == PermissionItem.TYPE_PHONE_STATE) {
            onContractSuitePermissionsContractSuiteRequestContractSuitePhoneStateContractSuitePass(true)
            if (isGrantedAll) {
                onContractSuitePermissionsContractSuiteRequestContractSuiteAllContractSuitePass()
            }

        } else if (requestCode == PermissionItem.TYPE_CONTRACTS) {
            onContractSuitePermissionsContractSuiteRequestContractSuiteContactsContractSuitePass(true)
            if (isGrantedAll) {
                onContractSuitePermissionsContractSuiteRequestContractSuiteAllContractSuitePass()
            }
        } else if (requestCode == PermissionItem.TYPE_CALL_LOG) {
            onContractSuitePermissionsContractSuiteRequestContractSuiteCalllogContractSuitePass(true)
            if (isGrantedAll) {
                onContractSuitePermissionsContractSuiteRequestContractSuiteAllContractSuitePass()
            }
        } else if (requestCode == REQ_CONTRACTSUITE_CODE_CONTRACTSUITE_PAGE_CONTRACTSUITE_PERMISSION) {
            onContractSuitePermissionsContractSuiteRequestContractSuiteAllContractSuitePass()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DEFAULT_SETTINGS_REQ_CODE) {
            mContractSuitePermissionContractSuiteStatement?.let {
                mContractSuitePermissionContractSuiteList?.let { list ->
                    startContractSuiteEasyContractSuitePermissions(it, list)
                }
            }
        }
    }

//    @AfterPermissionGranted(REQ_CONTRACTSUITE_CODE_CONTRACTSUITE_PAGE_CONTRACTSUITE_PERMISSION)
//    fun onContractSuiteEasyContractSuitePermissionsContractSuiteAllContractSuitePass() {
//        onContractSuitePermissionsContractSuiteRequestContractSuiteAllContractSuitePass()
//    }
//
//    @AfterPermissionGranted(PermissionItem.TYPE_SMS)
//    fun onContractSuiteEasyContractSuitePermissionsContractSuiteSMSContractSuitePass() {
//        onContractSuitePermissionsContractSuiteRequestContractSuiteSMSContractSuitePass(true)
//    }
//
//    @AfterPermissionGranted(PermissionItem.TYPE_HOME_SMS)
//    fun onContractSuiteEasyContractSuitePermissionsContractSuiteHomeSMSContractSuitePass() {
//        onContractSuitePermissionsContractSuiteRequestContractSuiteHomeSMSContractSuitePass(true)
//    }
//
//    @AfterPermissionGranted(PermissionItem.TYPE_PHONE_STATE)
//    fun onContractSuiteEasyContractSuitePermissionsContractSuitePhoneStateContractSuitePass() {
//        onContractSuitePermissionsContractSuiteRequestContractSuitePhoneStateContractSuitePass()
//    }


    protected fun startContractSuiteEasyContractSuitePermissions(
        reqStatement: String,
        permissionList: Array<String>
    ) {
        mContractSuitePermissionContractSuiteStatement = reqStatement
        mContractSuitePermissionContractSuiteList = permissionList

        EasyPermissions.requestPermissions(
            this,
            reqStatement,
            REQ_CONTRACTSUITE_CODE_CONTRACTSUITE_PAGE_CONTRACTSUITE_PERMISSION,
            *permissionList
        )
    }

    open fun isContractSuiteAllContractSuiteFormContractSuiteDataContractSuiteCompleted(): String {
        return ""
    }

}